<script setup>
import { onMounted, ref } from 'vue';
import dateUtil from '@/utils/dateUtil';
import chartApi from "@/api/chart.js";
import * as echarts from 'echarts';

const chartRef = ref();

onMounted(() => {
  const myChart = echarts.init(chartRef.value);

  // 本周第一天
  const date = dateUtil.getMonday();
  // 本周每一天
  const days = dateUtil.getWeekDays();

  // 图表配置
  let option = {
    title: {
      text: '课程预约人数对比图',
      textStyle: {
        color: '#161D23',
        fontWeight: 'bold',
        fontSize: 16,
      },
      left: '10px',
      top: '10px',
    },
    legend: {
      top: '20px',
      right: '20px',
      data: ['预约人数'], // 只显示预约人数
    },
    grid: {
      left: '3%',
      right: '30px',
      bottom: '3%',
      top: '60px',
      containLabel: true,
    },
    tooltip: {},
    yAxis: {
      type: 'value',
    },
    xAxis: {
      type: 'category',
      data: ['周一', '周二', '周三', '周四', '周五', '周六', '周日'],
      axisLabel: {color: '#161D23'},
    },
    series: [
      {
        name: '预约人数',
        type: 'bar',
        barWidth: '40%', // 柱子宽度
        data: [], // 后续填充
        label: {
          show: true,
          position: 'top',
          color: '#50CEFF',
        },
        backgroundStyle: {
          color: 'rgba(180,180,180,0.2)',
        },
      },
    ],
  };

  // 清空旧图表（防止残留）
  myChart.clear();

  // 获取预约人数数据
  chartApi.selectReserveCount(date).then(result => {
    const data = new Array(7).fill(0);
    for (let i = 0; i < days.length; i++) {
      for (let item of result.data) {
        if (item.day === days[i]) {
          data[i] = item.count;
        }
      }
    }
    option.series[0].data = data;
    myChart.setOption(option);
  });
});
</script>

<template>
  <div ref="chartRef" style="width: 100%; height: 100%;"></div>
</template>

<style>
/* 如果想让柱子和图表自适应，可以给父容器设置高度，例如 min-height */
</style>
